package com.icim.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import au.com.bytecode.opencsv.CSVWriter;

public class CsvFileWriterUtil {
    private static Logger logger = Logger.getLogger(CsvFileWriterUtil.class);


    public static void writeCVS(List<String[]> inputList, String fname) throws IOException {
        File tempFile = new File(fname);
        CSVWriter writer = new CSVWriter(new FileWriter(tempFile));
        writer.writeAll(inputList);
        writer.close();
        logger.info("Create And Write Success,fileName:" + fname);
    }
    
    public static void writeCVS(String[] headers, List<String[]> bodyList,String fname) throws IOException {
        File tempFile = new File(fname);
        List<String[]> inputList = new ArrayList<String[]>();
        inputList.add(headers);
        CSVWriter writer = new CSVWriter(new FileWriter(tempFile));
        inputList.addAll(bodyList);
        writer.writeAll(inputList);
        writer.close();
        logger.info("Create And Write Success,fileName:" + fname);
    }
    
    public static void writeCVS(String beginStr,String[] headers, List<String[]> bodyList,String endStr,String fname) throws IOException {
        File tempFile = new File(fname);
        List<String[]> inputList = new ArrayList<String[]>();
        inputList.add(new String[]{beginStr});
        inputList.add(headers);
        CSVWriter writer = new CSVWriter(new FileWriter(tempFile));
        inputList.addAll(bodyList);
        inputList.add(new String[]{endStr});
        writer.writeAll(inputList);
        writer.close();
        logger.info("Create And Write Success,fileName:" + fname);
    }

    public static void writeCVSWithMap(Map<Integer, ArrayList<Integer>> ma, String fname) throws IOException {
        File tempFile = new File(fname);
        CSVWriter writer = new CSVWriter(new FileWriter(tempFile));
        Set<Integer> key = ma.keySet();
        for (Iterator<Integer> it = key.iterator(); it.hasNext();) {
            int i = it.next();
            String[] tmp = new String[ma.get(i).size()];
            for (int j = 0; j < ma.get(i).size(); j++) {
                tmp[j] = Integer.toString(ma.get(i).get(j));
            }
            writer.writeNext(tmp);
        }

        writer.close();
    }

}
